package com.gridmobi.xrtb.routers.bidding;

import com.alibaba.fastjson.JSONObject;
import com.gridmobi.xrtb.domain.dsp.DspTrackLog;
import com.gridmobi.xrtb.domain.dsp.common.enums.ExchangesE;
import com.gridmobi.xrtb.dspcounter.DspCounterHandler;
import com.gridmobi.xrtb.handler.monitor.IpMonitor;
import com.gridmobi.xrtb.util.RtbUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/")
public class ImpressionController {
    private static final Logger logger = LoggerFactory.getLogger(ImpressionController.class);
    private static final Logger implog = LoggerFactory.getLogger("implog");
    private static final Logger errorlogger = LoggerFactory.getLogger("error");

    private static Map<String, Long> timestampMap = new HashMap<String, Long>();
    private static long MAX_TIME = 1000 * 60 * 60 * 24; // 1 Day
    private static Map<String, Integer> ctrMap = new HashMap<String, Integer>();
    private static int MIN_CTR = 400; // 40%
    private static int MAX_CTR = 900; // 90%
    @Autowired
    DspCounterHandler dspCounterHandler;

    @Autowired
    private IpMonitor ipMonitor;

    //    @Autowired
//    @Qualifier("kafkaBiddingLogger")
//    private BiddingLogger biddingLogger;

    // 展示通知
    @GetMapping("dspimpr")
    public void imp(@RequestParam Map<String, String> args, HttpServletRequest request, HttpServletResponse response) {

        try {

            LocalDateTime now = LocalDateTime.now();
            DspTrackLog trackArgs = RtbUtil.packTrackArgs(now, args, request);
            /*记录Imp*/
            if (trackArgs.getCid() == null) {
                trackArgs.setCid(request.getParameter("cid"));
            }
            dspCounterHandler.countImpr(Integer.parseInt(trackArgs.getCid()), trackArgs.getCrid(), trackArgs.getGeo(), trackArgs.getAppid(), trackArgs.getOs(), ExchangesE.getCode(trackArgs.getChannel()));
            /*
             * 记录用户展现次数
             */
            if (StringUtils.isEmpty(trackArgs.getCid()) || StringUtils.isEmpty(trackArgs.getDevid())) {
                errorlogger.warn("ImpsNull:", JSONObject.toJSONString(args));
            } else {


            }
     /*       Enumeration<String> headerNames = request.getHeaderNames();
            while (headerNames.hasMoreElements()) {
                String nextElement = headerNames.nextElement();
                String header2 = request.getHeader(nextElement);
                implog.warn(trackArgs.getBidId()+" : "+nextElement + ":" + header2);
                System.out.println(trackArgs.getBidId()+" : "+nextElement + ":" + header2);

            }
*/

            ;
            /**
             * ip  展现计数器，防止作弊
             */
            // ipMonitor.recordIp(trackArgs.getIp());
            if (trackArgs != null) {
//                biddingLogger.imprlog(trackArgs);
            }

            /*if (SimpleBidData.CAMPAIGN_IMPRURL.containsKey(trackArgs.getCid())) {
            	Random r = new Random();
            	Long time = timestampMap.get(trackArgs.getCid());
            	if (time==null) {
            		time = System.currentTimeMillis();
            	}
            	Integer ctr = ctrMap.get(trackArgs.getCid());
            	if (ctr==null || System.currentTimeMillis()-time > MAX_TIME) {
            		ctr = MIN_CTR + r.nextInt(MAX_CTR-MIN_CTR);
            		ctrMap.put(trackArgs.getCid(), ctr);
            		timestampMap.put(trackArgs.getCid(), System.currentTimeMillis());
            	}
            	if (ctr<MIN_CTR) {
            		ctr = MIN_CTR;
            	}
            	if (ctr>MAX_CTR) {
            		ctr = MAX_CTR;
            	}

                int campaignCtr = ctr.intValue();
            	int rate = r.nextInt(1000);
                logger.info("Impression Click Start cid:{}, ctr:{}, rate:{}", trackArgs.getCid(), campaignCtr, rate);
                if (rate<campaignCtr) {
                    logger.info("intoimpression:{}", SimpleBidData.CAMPAIGN_IMPRURL.get(trackArgs.getCid()));

                    ExecutorPool.getExecutor().execute(() -> {
                        try {
                            String userAgent = request.getHeader("User-Agent");
                            if(userAgent==null){
                                userAgent = "";
                            }
                            String trackurl = CampaignMonitor.CAMPAIGNS_LANDURL.get(trackArgs.getCid());

                            trackurl = MacrosTemplate.replaceTrackurl(trackurl, trackArgs, "");
                            logger.info("intotrack:{}", trackurl);

                            final String asynchTrackUrl = "http://jump.jinglemobi.com/request.do?type=click&geo=" + GEO_MAPPING.word3Map.get(trackArgs.getGeo()) + "&ua=" + URLEncoder.encode(userAgent, "utf-8") + "&url=" + URLEncoder.encode(trackurl, "utf-8");

                            logger.info(HttpClientUtil.getAndBodyAsJson(asynchTrackUrl).toJSONString());
                            logger.info("Impression Click End cid:{}, ctr:{}, rate:{}", trackArgs.getCid(), campaignCtr, rate);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    });
            	}
            }*/
        } catch (Exception e) {
            errorlogger.error("IMPERROR", e);
        }
        //implog.warn(JSONObject.toJSONString(args));
    }

}
